import {
	defineStore
} from 'pinia';
import {
	loginApi,
	getShopAccoutInfoApi,
	refreshApi,
	logout,
	checkAuthentication
} from '@/api/login.js'
import {
	getToken,
	setToken,
	clearToken
} from '@/utils/index.js'

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			token: getToken(),
			expire: '',
			respMallShopAccountDTO: {}, // 店铺账号信息
			respMallShopDTO: {}, // 店铺对象信息
		};
	},
	getters: {
		shopId: (state) => state?.respMallShopAccountDTO?.shopId,
		hasToken: (state) => !!state.token,
		// 客户认证 authentication  '是否认证 0=未认证 1=已认证'
		hasAuthentication: (state) => state.respMallShopDTO.authentication === 1,
		// 是否有用户信息
		hasUserInfo: (state) => state.respMallShopAccountDTO.username,
		// 当前是否是主账号 true是 false 否
		isMajor: (state) => state.respMallShopAccountDTO.major === 1
	},
	actions: {
		async login(data) {
			const res = await loginApi(data)
			this.token = res.token
			this.expire = res.expire
			setToken(res.token)
			await this.getUserInfo(false)
			await this.checkUser()
			return true
		},
		async checkUser() {
			try {
				await checkAuthentication()
				uni.switchTab({
					url: '/pages/home/index'
				})
			} catch (e) {
				uni.navigateTo({
					url: '/pages/login/customerInfo'
				})
			}
		},
		async refreshToken() {
			const res = await refreshApi()
			this.token = res.token
			this.expire = res.expire
			setToken(res.token)
		},
		async getUserInfo(isPath = true) {
			// if (this.hasUserInfo) return false
			const res = await getShopAccoutInfoApi()
			this.respMallShopAccountDTO = res.respMallShopAccountDTO
			this.respMallShopDTO = res.respMallShopDTO
			if (res.respMallShopDTO.authentication !== 1 && isPath) {
				uni.navigateTo({
					url: '/pages/login/customerInfo'
				})
			}
		},
		async clearData() {
			this.token = ''
			this.respMallShopAccountDTO = {}
			this.respMallShopDTO = {}
			clearToken()
		},
		async loginOut() {
			const _this = this
			uni.showModal({
				title: '提示',
				content: '确定退出登录吗?',
				success: async function (res) {
					if (res.confirm) {
						_this.loginOutFn()
					}
				}
			});
		},
		async loginOutFn() {
			await logout()
			this.clearData()
			uni.navigateTo({
				url: '/pages/login/index'
			})
		}
	},
});